import { DirectiveBinding } from 'vue';

/**
 * @date 2023-11-22 17:06:02
 * @desc  样式指令 支持所有样式
 * @param {Element} el dom
 * @param {any} binding 指令,获取binding.data
 */
export const styleDirective = (el: any, binding: DirectiveBinding<any>) => {
  // 过滤掉不需要的属性,这些属性不会参与样式的单位转换
  const excludeAttributes = ['font-weight', 'fontWeight', 'z-index', 'zIndex', 'data'];
  const data = binding.value;
  if (typeof data === 'string') {
    el.style.cssText = data.replace(/\d+(rpx|px)/g, (match: any) => {
      const number = match.match(/\d+/)![0]; // 提取数字部分
      return number2Vw(number); // 替换为数字
    });
  }
  if (typeof data === 'object' && data !== null && data.constructor === Object) {
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        //针对key为url时，默认加上背景
        if (key === 'url') {
          data['background-image'] ? '' : (data['background-image'] = `url(${data[key]})`);
          data['background-position'] ? '' : (data['background-position'] = `center`);
          data['background-repeat'] ? '' : (data['background-repeat'] = `no-repeat`);
          data['background-size'] ? '' : (data['background-size'] = `100% 100%`);
        }
      }
    }
    let cssText = '';
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        if (!excludeAttributes.includes(key)) {
          if (typeof data[key] === 'string') {
            data[key] = data[key].replace(/\d+(rpx|px)/g, (match) => {
              const number = match.match(/\d+/)![0]; // 提取数字部分
              return number2Vw(number); // 替换为数字
            });
          }
          if (typeof data[key] === 'number') {
            data[key] = number2Vw(data[key]);
          }
        }

        const replaceKey = key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
        data[replaceKey] = data[key]; //将驼峰改为横线
        cssText = cssText + `${replaceKey}:${data[replaceKey]};`;
      }
    }
    el.style.cssText = cssText;
  }
};

function number2Vw(number = 0) {
  return `${(100 * parseFloat(number.toString()) * (1 / 1920)).toFixed(5)}vw`;
}
